const { callbackify } = require('util');

/* 
    第一章 重构，第一个示例
    原始“坏”代码
    chapter 1
*/
function statement(invoice, plays) {
    let totalAmount = 0;
    let volumeCredits = 0;
    let result = "Statement for " + invoice.customer + "\n";

    const format = new Intl.NumberFormat("en-US", {
        style: "currency", currency: "USD",
        minimumFractionDigits: 2
    }).format;

    for (let perf of invoice.performance) {
        const play = plays[perf.playID];
        let thisAmount = 0;

        switch (play.type) {
            case "tragedy":
                thisAmount = 40000;
                if (perf.audience > 30) {
                    thisAmount += 1000 * (perf.audience - 30);
                }
                break;
            case "comedy":
                thisAmount = 3000;
                if (perf.audience > 20) {
                    thisAmount += 1000 + 500 * (perf.audience - 20);
                }
                break;
            default:
                throw new Error("unknown type:" + play.type);
        }

        // add volume credits
        volumeCredits += Math.max(perf.audience - 30, 0);
        // add extra credit for every ten comedy attendees
        if ("comedy" === play.type) {
            volumeCredits += Math.floor(perf.audience/5);
        }

        // print line for this order 
        result += "-- " + play.name + ": " + format(thisAmount / 100) + " (" + perf.audience + " seats)" + "\n";
        totalAmount += thisAmount;
    };
    result += "Amount owed id " + format(totalAmount / 100) + "\n";
    result += "You earned " + volumeCredits + " credits";
    console.log(result);
    return result;
}

/****************************************** */
function readJson(fileName, callback) {
    var fs = require('fs');
    fs.readFile(fileName, 'utf-8', (err, data) => {
        if (err) {
            console.error(err);
        } else {
            callback(JSON.parse(data));
        }
    });
}

var invoice;
var play;
readJson("invoices.json", (myData) => {
    invoice = myData;
});
readJson("play.json", (myData) => {
    play = myData;
});
var timer = setInterval(() => {
    if (invoice) {
        clearInterval(timer);
        // console.log({ invoice });
        // console.log({ play });
        statement(invoice, play);
    }
}, 500);
